﻿using AnlianCommon.API.Commands.Personnels;
using AnlianCommon.Common.Domains.SheepFarmHouse;
using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Cottages
{
    public class CottageSearchHander: IRequestHandler<CottageSearchCommand, ResultPage<Cottage>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<Cottage> _cottageRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="personnelRepository"></param>
        /// <param name="mapper"></param>
        public CottageSearchHander(IBaseRepository<Cottage> _cottageRepository, IMapper mapper)
        {
            this._cottageRepository = _cottageRepository;
            this._mapper = mapper;
        
        }

        /// <summary>
        /// 栋舍显示列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Cottage>> Handle(CottageSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Cottage>() { Code = (int)CommonErrorCode.Search, TotalCount = 0, PagedCount = 0 };
            try
            {
                var coottage = await(await _cottageRepository.GetAll()).ToListAsync();
                if (!string.IsNullOrEmpty(request.CottageName))
                {
                    coottage = coottage.Where(p => p.CottageName.Contains(request.CottageName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.CottageTypeId))
                {
                    coottage = coottage.Where(p => p.CottageTypeId == request.CottageTypeId).ToList();
                }
                if (!string.IsNullOrEmpty(request.PersId))
                {
                    coottage = coottage.Where(p => p.PersId == request.PersId).ToList();
                }
                result.TotalCount = coottage.Count;
                result.PagedCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                coottage = coottage.OrderByDescending(c => c.CottageId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = coottage;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
